package com.yaodian100.ec.supplierapply.web;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.aspectj.util.FileUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.userdetails.UserDetails;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.Preparable;
import com.yaodian100.core.admin.entity.Role;
import com.yaodian100.core.admin.utils.AdminHelper;
import com.yaodian100.core.common.dao.impl.CommonCriteria;
import com.yaodian100.core.common.entity.SimplePager;
import com.yaodian100.core.menu.entity.Menu;
import com.yaodian100.core.menu.service.MenuService;
import com.yaodian100.ec.category.entity.Category;
import com.yaodian100.ec.category.service.CategoryService;
import com.yaodian100.ec.supplierapply.entity.NewSupplierApply;
import com.yaodian100.ec.supplierapply.entity.SupplierApplyPhoto;
import com.yaodian100.ec.supplierapply.service.NewSupplierApplyService;

/**
 * @author Tina.xu
 * 
 */
public class NewSupplierApplyAction extends ActionSupport implements Preparable {

	@Resource(name = "newSupplierApplyService")
	private NewSupplierApplyService newsupplierApplyService;
	@Autowired
	private MenuService menuService;
	@Autowired
	private CategoryService categoryService;
	private Menu menuPaymentBankArea;// 付款銀行所在地
	private Menu menuArea;// 區域
	private Menu menuCurrency;// 幣別
	private Menu menuPaymentTerm;
	private Menu menuIncoterm;// Incoterm
	private Menu menuTaxInvoice;// 納稅人性質/發票性質
	private Menu menuApplyStatus;// 审核状态
	private List<Category> rootCategories;// 館分類
	private NewSupplierApply newsupplierapply;
	private List<SupplierApplyPhoto> nasphotoList;
	private List<NewSupplierApply> newsupplierapplyList;
	private CommonCriteria criteria;

	private String photoid;
	private String keyword;
	private String esyear;
	private String esmonth;
	private String estime;
	private String[] photoDelete;

	private String saveResult = "";
	private Integer approveStatus;
	private File image;
	private File image1;
	private File image2;
	private File image3;
	private File image4;
	private String imageContentType;
	private String image1ContentType;
	private String image2ContentType;
	private String image3ContentType;
	private String image4ContentType;
	private String imageFileName;
	private String image1FileName;
	private String image2FileName;
	private String image3FileName;
	private String image4FileName;
	private String imageDecription;
	private String imageDecription1;
	private String imageDecription2;
	private String imageDecription3;
	private String imageDecription4;
	private String supplierID;
	private SimplePager pager;
	private int fileSize = 1024;
	private List<NewSupplierApply.Type> bototype = Arrays.asList(NewSupplierApply.Type.O, NewSupplierApply.Type.V,
			NewSupplierApply.Type.OV);

	public String search() {
		try {
			criteria = new CommonCriteria();
			if (StringUtils.isNotBlank(keyword)) {
				criteria.addRlike("companyName", keyword.trim());
			}

			if (approveStatus != null) {
				criteria.addEq("status", approveStatus);
			} else {
				List<Integer> statusIn = new ArrayList();
				statusIn.add(0);
				statusIn.add(1);
				statusIn.add(2);
				statusIn.add(9);
				criteria.addIn("status", statusIn);
			}

			if (pager == null) {
				pager = new SimplePager();
			}

			int entitySize = newsupplierApplyService.getListSize(criteria).intValue();
			pager.setTotalSize(entitySize);

			newsupplierapplyList = newsupplierApplyService.getList(pager.getCurrentPage() * pager.getPageRecord(), pager
					.getPageRecord(), criteria, null);
		} catch (Exception e) {
			addActionError("搜寻失败：" + e.getMessage());
		}
		return "list";
	}

	public String add() {
		newsupplierapply = new NewSupplierApply();
		photoDelete = null;
		esyear = "";
		esmonth = "";
		estime = "";
		image = null;
		image1 = null;
		image2 = null;
		image3 = null;
		image4 = null;
		imageDecription4 = "";
		imageDecription3 = "";
		imageDecription2 = "";
		imageDecription1 = "";
		imageDecription = "";
		return "editst0";
	}

	public String save() {
		try {
			if (newsupplierapply.getSupplierID() != null && !newsupplierapply.getSupplierID().equals(supplierID)) {
				if (StringUtils.isBlank(supplierID)) {
					addActionError("● 资料新增错误, 请重新填写, 请勿同时操作两视窗");
					return add();
				} else {
					addActionError("● 资料异动错误, 回覆原始资料, 请勿同时操作两视窗");
					newsupplierapply = newsupplierApplyService.get(supplierID);
				}
				if (newsupplierapply.getStatus() == 0) {
					return "editst0";
				} else {
					return "editst1";
				}
			}
			if (StringUtils.isNotBlank(esyear) && StringUtils.isNotBlank(esmonth)) {
				estime = esyear.trim() + "-" + esmonth.trim();
				newsupplierapply.setCompanyesttime(estime);
			}
			try {
				newsupplierApplyService.save(newsupplierapply);
				if (StringUtils.isNotBlank(supplierID)) {
					addActionMessage("● 资料已修改成功");
				} else {
					addActionMessage("● 资料已新增成功");
				}
			} catch (Exception e) {
				addActionMessage("● 资料修改失败");
			}

			if (newsupplierapply.getSupplierID() != null) {
				try {
					if (image != null && imageDecription != null) {
						if ((image.length() / 1024) > fileSize) {
							addActionMessage("● 档案一「" + imageFileName + "」上传失败，原因是：档案大小超出限制");
						} else {
							byte[] finp = FileUtil.readAsByteArray(image);
							newsupplierApplyService.saveforPhoto(newsupplierapply, finp, imageDecription, imageFileName);
							addActionMessage("● 档案一「" + imageFileName + "」上传成功");
						}
					}

				} catch (Exception e) {
					addActionMessage("● 档案一「" + imageFileName + "」上传失败，原因是：" + e.getMessage());
				}
				try {
					if (image1 != null && imageDecription1 != null) {
						if ((image1.length() / 1024) > fileSize) {
							addActionMessage("● 档案二「" + imageFileName + "」上传失败，原因是：档案大小超出限制");
						} else {
							byte[] finp = FileUtil.readAsByteArray(image1);
							newsupplierApplyService.saveforPhoto(newsupplierapply, finp, imageDecription1, image1FileName);
							addActionMessage("● 档案二「" + image1FileName + "」上传成功");
						}
					}

				} catch (Exception e) {
					addActionMessage("● 档案二「" + image1FileName + "」上传失败，原因是：" + e.getMessage());
				}
				try {
					if (image2 != null && imageDecription2 != null) {
						if ((image2.length() / 1024) > fileSize) {
							addActionMessage("● 档案三「" + imageFileName + "」上传失败，原因是：档案大小超出限制");
						} else {
							byte[] finp = FileUtil.readAsByteArray(image2);
							newsupplierApplyService.saveforPhoto(newsupplierapply, finp, imageDecription2, image2FileName);
							addActionMessage("● 档案三「" + image2FileName + "」上传成功");
						}
					}

				} catch (Exception e) {
					addActionMessage("● 档案三「" + image2FileName + "」上传失败，原因是：" + e.getMessage());
				}

				try {
					if (image3 != null && imageDecription3 != null) {
						if ((image3.length() / 1024) > fileSize) {
							addActionMessage("● 档案四「" + imageFileName + "」上传失败，原因是：档案大小超出限制");
						} else {
							byte[] finp = FileUtil.readAsByteArray(image3);
							newsupplierApplyService.saveforPhoto(newsupplierapply, finp, imageDecription3, image3FileName);
							addActionMessage("● 档案四「" + image3FileName + "」上传成功");
						}
					}
				} catch (Exception e) {
					addActionMessage("● 档案四「" + image3FileName + "」上传失败，原因是：" + e.getMessage());
				}

				try {
					if (image4 != null && imageDecription4 != null) {
						if ((image4.length() / 1024) > fileSize) {
							addActionMessage("● 档案五「" + imageFileName + "」上传失败，原因是：档案大小超出限制");
						} else {
							byte[] finp = FileUtil.readAsByteArray(image4);
							newsupplierApplyService.saveforPhoto(newsupplierapply, finp, imageDecription4, image4FileName);
							addActionMessage("● 档案五「" + image4FileName + "」上传成功");
						}
					}
				} catch (Exception e) {
					addActionMessage("● 档案五「" + image4FileName + "」上传失败，原因是：" + e.getMessage());
				}
			}

			try {
				if (null != photoDelete) {
					for (int i = 0; i < photoDelete.length; i++) {
						String photoName = newsupplierApplyService.getPhoto(photoDelete[i]).getFilename();
						newsupplierApplyService.deleteforPhoto(photoDelete[i]);
						addActionMessage("● 档案「" + photoName + "」删除成功");
					}
				}
			} catch (Exception e) {
				addActionMessage("● 档案删除失败:" + e.getMessage());
			}

			nasphotoList = newsupplierApplyService.getPhotos(newsupplierapply.getSupplierID());
			photoDelete = null;
			image = null;
			image1 = null;
			image2 = null;
			image3 = null;
			image4 = null;
			imageDecription4 = "";
			imageDecription3 = "";
			imageDecription2 = "";
			imageDecription1 = "";
			imageDecription = "";
			if (StringUtils.isBlank(supplierID)) {
				return "view";
			} else {
				if (newsupplierapply.getStatus() == 0) {
					return "editst0";
				} else {
					return "editst1";
				}
			}
		} catch (Exception e) {
			if (newsupplierapply.getStatus() == 0) {
				addActionError("● 儲存失敗:" + e.getMessage());
				return "editst0";
			} else if (newsupplierapply.getStatus() == 1) {
				addActionError("● 儲存失敗:" + e.getMessage());
				return "editst1";
			} else {
				addActionError("● 新增失敗:" + e.getMessage());
				return "editst0";
			}
		}
	}

	public String st0pass() {
		try {
			if (newsupplierapply.getStatus().equals(0)) {
				UserDetails user = AdminHelper.getUserDetails();
				newsupplierapply.setApproveByPd(user.getUsername());
				newsupplierApplyService.approve1(newsupplierapply);
				setSaveResult("此供应商状态已修改为：采购部已核可!");
				return "jsonSave";
			} else {
				setSaveResult("狀態變更錯誤");
				return "jsonSave";
			}
		} catch (Exception e) {
			setSaveResult("審核失敗:" + e.getMessage());
			return "jsonSave";
		}

	}

	public String st1pass() {
		try {
			if (newsupplierapply.getStatus() == 1) {
				UserDetails user = AdminHelper.getUserDetails();
				newsupplierapply.setApproveByPm(user.getUsername());
				newsupplierApplyService.approve2(newsupplierapply);
				setSaveResult("此供应商状态已修改为：PM已核可!");
				return "jsonSave";

			} else {
				setSaveResult("狀態變更錯誤");
				return "jsonSave";
			}
		} catch (Exception e) {
			setSaveResult("審核失敗:" + e.getMessage());
			return "jsonSave";
		}
	}

	public String reject() {
		try {
			if (newsupplierapply.getStatus() < 9 && newsupplierapply.getStatus() != 2) {
				UserDetails user = AdminHelper.getUserDetails();
				if (newsupplierapply.getStatus() == 0) {
					newsupplierapply.setApproveByPd(user.getUsername());
				}
				if (newsupplierapply.getStatus() == 1) {
					newsupplierapply.setApproveByPm(user.getUsername());
				}
				newsupplierapply.setStatus(9);
				newsupplierApplyService.save(newsupplierapply);
				setSaveResult("此供应商状态已改为：审核不通过");
				return "jsonSave";
			} else {
				setSaveResult("此供應商無法再更改狀態");
				return "jsonSave";
			}
		} catch (Exception e) {
			setSaveResult("不通過失敗:" + e.getMessage());
			return "jsonSave";
		}
	}

	public String view() {
		try {
			if (supplierID.length() > 0) {
				newsupplierapply = newsupplierApplyService.get(supplierID);
				nasphotoList = newsupplierApplyService.getPhotos(supplierID);
				return "view";
			} else {
				addActionError("● 查無資料");
				return search();
			}
		} catch (Exception e) {
			addActionError("● 查看失敗:" + e.getMessage());
			return search();
		}
	}

	public String edit() {
		try {
			if (supplierID != null) {
				newsupplierapply = newsupplierApplyService.get(supplierID);
				nasphotoList = newsupplierApplyService.getPhotos(supplierID);
				if (newsupplierapply.getCompanyesttime() != null) {
					esyear = newsupplierapply.getCompanyesttime().substring(0, 4);
					esmonth = newsupplierapply.getCompanyesttime().substring(5);
				}
				if (newsupplierapply != null) {
					if (AdminHelper.hasPermission("Group_A-30-300-000") && newsupplierapply.getStatus() == 0) {
						return "editst0";
					} else if (AdminHelper.hasRole("PM", Role.Type.OTHER) && newsupplierapply.getStatus() == 1) {
						if (StringUtils.isNotBlank(newsupplierapply.getCategory())
								&& AdminHelper.hasPermission("CATEGORY_" + newsupplierapply.getCategory())) {
							return "editst1";
						} else {
							return "view";
						}
					} else {
						return "view";
					}
				} else {
					addActionError("● 查無資料");
					return search();
				}
			} else {
				addActionError("● id為空");
				return search();
			}
		} catch (Exception e) {
			addActionError("● 編輯失敗:" + e.getMessage());
			return search();
		}
	}

	@Override
	public void prepare() throws Exception {
		clearErrorsAndMessages();
		if (rootCategories == null) {
			rootCategories = categoryService.getChild(Long.parseLong("0"));
		}

		if (menuPaymentTerm == null) {
			menuPaymentTerm = menuService.get("Supplier.paymentTerm");
		}

		if (menuApplyStatus == null) {
			menuApplyStatus = menuService.get("NewSupplier.approveStatus");
		}
		if (menuArea == null) {
			menuArea = menuService.get("Supplier.area");
		}
		if (menuCurrency == null) {
			menuCurrency = menuService.get("Common.Currency");
		}
		if (menuIncoterm == null) {
			menuIncoterm = menuService.get("Common.Incoterm");
		}
		if (menuTaxInvoice == null) {
			menuTaxInvoice = menuService.get("Supplier.taxInvoice");
		}
		if (menuPaymentBankArea == null) {
			menuPaymentBankArea = menuService.get("PaymentBank.Area");
		}
	}

	public MenuService getMenuService() {
		return menuService;
	}

	public void setMenuService(MenuService menuService) {
		this.menuService = menuService;
	}

	public List<Category> getRootCategories() {
		return rootCategories;
	}

	public void setRootCategories(List<Category> rootCategories) {
		this.rootCategories = rootCategories;
	}

	public List<NewSupplierApply> getNewsupplierapplyList() {
		return newsupplierapplyList;
	}

	public void setNewsupplierapplyList(List<NewSupplierApply> newsupplierapplyList) {
		this.newsupplierapplyList = newsupplierapplyList;
	}

	public String getSupplierID() {
		return supplierID;
	}

	public void setSupplierID(String supplierID) {
		this.supplierID = supplierID;
	}

	public String getKeyword() {
		return keyword;
	}

	public void setKeyword(String keyword) {
		this.keyword = keyword;
	}

	public SimplePager getPager() {
		return pager;
	}

	public void setPager(SimplePager pager) {
		this.pager = pager;
	}

	public List<SupplierApplyPhoto> getNasphotoList() {
		return nasphotoList;
	}

	public void setNasphotoList(List<SupplierApplyPhoto> nasphotoList) {
		this.nasphotoList = nasphotoList;
	}

	public String getPhotoid() {
		return photoid;
	}

	public void setPhotoid(String photoid) {
		this.photoid = photoid;
	}

	public Menu getMenuApplyStatus() {
		return menuApplyStatus;
	}

	public Integer getApproveStatus() {
		return approveStatus;
	}

	public void setApproveStatus(Integer approveStatus) {
		this.approveStatus = approveStatus;
	}

	public String getImageDdecription() {
		return imageDecription;
	}

	public void setImageDdecription(String imageDdecription) {
		this.imageDecription = imageDdecription;
	}

	public String getEsyear() {
		return esyear;
	}

	public void setEsyear(String esyear) {
		this.esyear = esyear;
	}

	public String getEsmonth() {
		return esmonth;
	}

	public void setEsmonth(String esmonth) {
		this.esmonth = esmonth;
	}

	public String getEstime() {
		return estime;
	}

	public void setEstime(String estime) {
		this.estime = estime;
	}

	public NewSupplierApply getNewsupplierapply() {
		return newsupplierapply;
	}

	public void setNewsupplierapply(NewSupplierApply newsupplierapply) {
		this.newsupplierapply = newsupplierapply;
	}

	public List<NewSupplierApply.Type> getBototype() {
		return bototype;
	}

	public void setBototype(List<NewSupplierApply.Type> bototype) {
		this.bototype = bototype;
	}

	public String getSaveResult() {
		return saveResult;
	}

	public void setSaveResult(String saveResult) {
		this.saveResult = saveResult;
	}

	public Menu getMenuPaymentBankArea() {
		return menuPaymentBankArea;
	}

	public Menu getMenuArea() {
		return menuArea;
	}

	public Menu getMenuCurrency() {
		return menuCurrency;
	}

	public Menu getMenuPaymentTerm() {
		return menuPaymentTerm;
	}

	public Menu getMenuIncoterm() {
		return menuIncoterm;
	}

	public Menu getMenuTaxInvoice() {
		return menuTaxInvoice;
	}

	public void setImage(File image) {
		this.image = image;
	}

	public void setImage1(File image1) {
		this.image1 = image1;
	}

	public String[] getPhotoDelete() {
		return photoDelete;
	}

	public void setPhotoDelete(String[] photoDelete) {
		this.photoDelete = photoDelete;
	}

	public void setImage2(File image2) {
		this.image2 = image2;
	}

	public void setImage3(File image3) {
		this.image3 = image3;
	}

	public void setImage4(File image4) {
		this.image4 = image4;
	}

	public void setImage1FileName(String image1FileName) {
		this.image1FileName = image1FileName;
	}

	public void setImage2FileName(String image2FileName) {
		this.image2FileName = image2FileName;
	}

	public void setImage3FileName(String image3FileName) {
		this.image3FileName = image3FileName;
	}

	public void setImage4FileName(String image4FileName) {
		this.image4FileName = image4FileName;
	}

	public void setImageContentType(String imageContentType) {
		this.imageContentType = imageContentType;
	}

	public void setImage1ContentType(String image1ContentType) {
		this.image1ContentType = image1ContentType;
	}

	public void setImage2ContentType(String image2ContentType) {
		this.image2ContentType = image2ContentType;
	}

	public void setImage3ContentType(String image3ContentType) {
		this.image3ContentType = image3ContentType;
	}

	public void setImage4ContentType(String image4ContentType) {
		this.image4ContentType = image4ContentType;
	}

	public String getImageFileName() {
		return imageFileName;
	}

	public void setImageFileName(String imageFileName) {
		this.imageFileName = imageFileName;
	}

	public File getImage() {
		return image;
	}

	public File getImage1() {
		return image1;
	}

	public File getImage2() {
		return image2;
	}

	public File getImage3() {
		return image3;
	}

	public File getImage4() {
		return image4;
	}

	public String getImageContentType() {
		return imageContentType;
	}

	public String getImage1ContentType() {
		return image1ContentType;
	}

	public String getImage2ContentType() {
		return image2ContentType;
	}

	public String getImage3ContentType() {
		return image3ContentType;
	}

	public String getImage4ContentType() {
		return image4ContentType;
	}

	public String getImage1FileName() {
		return image1FileName;
	}

	public String getImage2FileName() {
		return image2FileName;
	}

	public String getImage3FileName() {
		return image3FileName;
	}

	public String getImage4FileName() {
		return image4FileName;
	}

	public String getImageDecription() {
		return imageDecription;
	}

	public void setImageDecription(String imageDecription) {
		this.imageDecription = imageDecription;
	}

	public String getImageDecription1() {
		return imageDecription1;
	}

	public void setImageDecription1(String imageDecription1) {
		this.imageDecription1 = imageDecription1;
	}

	public String getImageDecription2() {
		return imageDecription2;
	}

	public void setImageDecription2(String imageDecription2) {
		this.imageDecription2 = imageDecription2;
	}

	public String getImageDecription3() {
		return imageDecription3;
	}

	public void setImageDecription3(String imageDecription3) {
		this.imageDecription3 = imageDecription3;
	}

	public String getImageDecription4() {
		return imageDecription4;
	}

	public void setImageDecription4(String imageDecription4) {
		this.imageDecription4 = imageDecription4;
	}

	public int getFileSize() {
		return fileSize;
	}

	public void setFileSize(int fileSize) {
		this.fileSize = fileSize;
	}

}
